package com.imooc.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 * https://blog.csdn.net/qq_42236784/article/details/127004137
 * @author gzj
 * @since 2022/10/9
 */
@Slf4j
public class PdfUtils {

    /**
     * @description
     *	给PDF文档添加水印浏览器
     * @author TianwYam
     * @date 2021年4月28日上午10:00:05
     */
    public static void addWaterMarkWeb(String pdfFilePath, HttpServletResponse response) throws UnsupportedEncodingException {

        PdfStamper stamper = null;
        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfReader reader = null;
        String fileName =  "test.pdf";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment;fileName="+fileName);
        try {
            out = response.getOutputStream();
            bos = new ByteArrayOutputStream();;
            // 原PDF文件
            reader = new PdfReader(pdfFilePath);
            // 输出的PDF文件内容
            stamper = new PdfStamper(reader, bos);

            // 字体 来源于 itext-asian JAR包
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);

            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.4f);

            int totalPage = reader.getNumberOfPages() + 1;
            for (int i = 1; i < totalPage; i++) {
                // 内容上层
//			PdfContentByte content = stamper.getOverContent(i);
                // 内容下层
                PdfContentByte content = stamper.getUnderContent(i);

                content.beginText();
                // 字体添加透明度
                content.setGState(gs);
                // 添加字体大小等
                content.setFontAndSize(baseFont, 50);
                // 添加范围
                content.setTextMatrix(70, 200);
                // 具体位置 内容 旋转多少度 共360度
                content.showTextAligned(Element.ALIGN_CENTER, "李洪江", 300, 350, 300);
                content.showTextAligned(Element.ALIGN_TOP, "李洪江", 100, 100, 5);
                content.showTextAligned(Element.ALIGN_BOTTOM, "李洪江", 400, 400, 75);

                content.endText();
            }
            stamper.close();

            // 将ByteArray字节数组中的流输出到out中（即输出到浏览器）
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }


    /**
     * @description
     *	给PDF文档添加水印本地
     * @author TianwYam
     * @date 2021年4月28日上午10:00:05
     */
    public static void addWatermarkLocalHost(String pdfFilePath, String outputFilePath, HttpServletResponse response) {
        try {
            // 原PDF文件
            PdfReader reader = new PdfReader(pdfFilePath);
            // 输出的PDF文件内容
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath));

            // 字体 来源于 itext-asian JAR包
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=test.pdf");
            OutputStream out = response.getOutputStream();
            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.4f);

            int totalPage = reader.getNumberOfPages() + 1;
            for (int i = 1; i < totalPage; i++) {
                // 内容上层
//			PdfContentByte content = stamper.getOverContent(i);
                // 内容下层
                PdfContentByte content = stamper.getUnderContent(i);
                content.beginText();
                // 字体添加透明度
                content.setGState(gs);
                // 添加字体大小等
                content.setFontAndSize(baseFont, 50);
                // 添加范围
                content.setTextMatrix(70, 200);
                // 具体位置 内容 旋转多少度 共360度
                content.showTextAligned(Element.ALIGN_CENTER, "机密文件", 300, 350, 300);
                content.showTextAligned(Element.ALIGN_TOP, "机密文件", 100, 100, 5);
                content.showTextAligned(Element.ALIGN_BOTTOM, "机密文件", 400, 400, 75);

                content.endText();
            }

            // 关闭
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据模版生成pdf带本地
     * @throws UnsupportedEncodingException
     * @throws FileNotFoundException
     */
    public static void createPdf()throws UnsupportedEncodingException, FileNotFoundException {
        // 模板名称
        String templateName = "repost_pass_template.pdf";
        String path = "";
        // 获取操作系统名称，根据系统名称确定模板存放的路径
        String systemName = System.getProperty("os.name");
        if(systemName.toUpperCase().startsWith("WIN")){
            path = "C:\\Users\\Administrator\\Desktop\\";
        }else {
            path = "/usr/local/pdf/";
        }
        // 生成导出PDF的文件名称
        String fileName =  "test.pdf";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        PdfReader reader = null;
        try {
            // 保存到本地
            out = new FileOutputStream(fileName);
            // 读取PDF模板表单
            reader = new PdfReader(path + templateName);
            // 字节数组流，用来缓存文件流
            bos = new ByteArrayOutputStream();
            // 根据模板表单生成一个新的PDF
            stamper = new PdfStamper(reader, bos);
            // 获取新生成的PDF表单
            AcroFields form = stamper.getAcroFields();
            // 给表单生成中文字体，这里采用系统字体，不设置的话，中文显示会有问题
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(font);
            // 装配数据
            Map<String, Object> data = new HashMap<>(15);
            data.put("reportNo", "1322222");
            data.put("reportTime", "李洪江");
            data.put("riskVersion", "李洪江.getSex()");
            data.put("whiteVersion","admissionCard.getIdCard()");
            data.put("strategyNo", "admissionCard.getSchool()");
            data.put("name", "admissionCard.getEnterSchool()");
            data.put("phone", "admissionCard.getExamAddress()");
            data.put("idCard", "admissionCard.getMajor()");
            data.put("reviewScore", "admissionCard.getEnterName()");
            data.put("whiteQuota", "admissionCard.getStudentImg()");
            data.put("riskQuota", "admissionCard.getStudentImg()");
            data.put("reviewQuota", "admissionCard.getStudentImg()");
            data.put("deviationDegree", "admissionCard.getStudentImg()");
            // 遍历data，给pdf表单赋值
            for(String key : data.keySet()){
                // 图片要单独处理
                if("studentImg".equals(key)){
                    int pageNo = form.getFieldPositions(key).get(0).page;
                    Rectangle signRect = form.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    String studentImage = data.get(key).toString();
                    //根据路径或Url读取图片
                    Image image = Image.getInstance(studentImage);
                    //获取图片页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    //图片大小自适应
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    //添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                }
                 //设置普通文本数据
                else {
                form.setField(key, data.get(key).toString());
                }
            }
            // 表明该PDF不可修改
            stamper.setFormFlattening(true);
            // 关闭资源
            stamper.close();
            // 将ByteArray字节数组中的流输出到out中（即输出到浏览器）
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            log.info("*****************************PDF导出成功*********************************");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据模版生成pdf到本地环境
     * @param response
     * @throws UnsupportedEncodingException
     * @throws FileNotFoundException
     */
    public static void createPdf2(HttpServletResponse response)throws UnsupportedEncodingException, FileNotFoundException {
        // 模板名称
        String templateName = "repost_pass_template.pdf";
        String path = "";
        // 获取操作系统名称，根据系统名称确定模板存放的路径
        String systemName = System.getProperty("os.name");
        if(systemName.toUpperCase().startsWith("WIN")){
            path = "C:\\Users\\Administrator\\Desktop\\";
        }else {
            path = "/usr/local/pdf/";
        }
        // 生成导出PDF的文件名称
        String fileName = "test.pdf";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + fileName);
        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        PdfReader reader = null;
        try {
            // 输出到浏览器端
            out = response.getOutputStream();
            // 读取PDF模板表单
            reader = new PdfReader(path + templateName);
            // 字节数组流，用来缓存文件流
            bos = new ByteArrayOutputStream();
            // 根据模板表单生成一个新的PDF
            stamper = new PdfStamper(reader, bos);
            // 获取新生成的PDF表单
            AcroFields form = stamper.getAcroFields();
            // 给表单生成中文字体，这里采用系统字体，不设置的话，中文显示会有问题
            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(font);
            // 装配数据
            Map<String, Object> data = new HashMap<>(15);
            data.put("reportNo", "李洪江");
            data.put("reportTime", "admissionCard.getName()");
            data.put("riskVersion", "admissionCard.getSex()");
            data.put("whiteVersion","admissionCard.getIdCard()");
            data.put("strategyNo", "admissionCard.getSchool()");
            data.put("name", "admissionCard.getEnterSchool()");
            data.put("phone", "admissionCard.getExamAddress()");
            data.put("idCard", "admissionCard.getMajor()");
            data.put("reviewScore", "admissionCard.getEnterName()");
            data.put("whiteQuota", "admissionCard.getStudentImg()");
            data.put("riskQuota", "admissionCard.getStudentImg()");
            data.put("reviewQuota", "admissionCard.getStudentImg()");
            data.put("deviationDegree", "admissionCard.getStudentImg()");
            // 遍历data，给pdf表单赋值
            for(String key : data.keySet()){
                form.setField(key, data.get(key).toString());
            }
            // 表明该PDF不可修改
            stamper.setFormFlattening(true);
            // 关闭资源
            stamper.close();
            // 将ByteArray字节数组中的流输出到out中（即输出到浏览器）
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            log.info("*****************************PDF导出成功*********************************");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


}
